<?php

namespace G659\Controller;

use Think\Controller;

class IndexController extends CommonController {

    public function index($c = 38) {
        $data['shiji'] = $this->shiji_return($c);
        $data['tree'] = $this->display_return($c);


        foreach ($data['tree'] as $v) {
            if ($c == 38) {
                $this->title = '供应商基本信息';
            } else {
                $this->title = '查看&编辑：' . $v['name'];
            }
        }
        $this->door = ( M('t')->join('u on u.id_c=t.id')->field('concat("index/index?c=",t.id)door,t.name,count(u.id)u_count')->group('t.id')
                        ->where(['u.id_g' => session('user.id'), 'u.id_c' => array('neq', '38')])->select());

        if (IS_POST) {
            $data['door'] = $this->door;
            $this->ajaxReturn($data);
        } else {
            $this->data = json_encode($data['shiji']);
            $this->c = $c;

            // print_r($door);exit;
            $this->display();
        }
    }

    public function shiji_return($c = 38) {
        $data = M('u')
                ->join('left join display on display.id_c=u.id_c')
                ->join('left join shiji on shiji.id_u=u.id and shiji.id_display=display.id')
                ->field('u.id,u.sku,'
                        . 'display.id display,tag,select_data,type,if(type like "*%",left(type,1),null)bixu,if(type like "%adds%","adds",null)adds,'
                        . 'shiji.id shiji,str')
                ->where(['u.id_g' => session('user.id'), 'u.id_c' => $c])
                ->order('u.id desc,display.orderby asc')
                ->select();

        foreach ($data as $v) {
            $select_data = explode('|', $v['select_data']);
            foreach ($select_data as $k2 => $v2) {
                $select_data[$k2] = explode('/', $v2);
            }
            if (!$v['str']) {
                $v['str'] = implode('/', $select_data[0]);
            }

            $shiji[$v['id'] . '/' . $v['display']][] = [
                'shiji' => $v['shiji'],
                'str' => $v['str']// //前端处理：
                    //str包含"管理员问"默认shiji_add;
                    //str包含"逐条添加"默认打开tree
            ];

            $display[$v['id']][$v['display']] = [
                'display' => $v['display'],
                'tag' => $v['tag'],
                'type' => $v['type'],
                'shiji' => [],
                'bixu' => strpos($v['type'], '*') === false ? "" : '*',
                'adds' => strpos($v['type'], 'adds') === false ? "" : 'adds',
                'select_data' => $select_data,
            ];
            $sku[$v['id']] = $v['sku'];
        }

        foreach ($display as $k => $v) {
            foreach ($v as $k2 => $s) {
                $v[$k2]['shiji'] = $shiji[$k . '/' . $k2];
            }
            $newdata[] = [
                'id' => $k, //加一个sku字段
                'sku' => $sku[$k],
                'display' => array_values($v)
            ];
        }
        return $newdata;
    }

    public function display_return($c = 38) {
        if ($c !== 38) {
            $map['t.id'] = $c;
        }
        $data = M('t')->join('left join display on display.id_c=t.id')
                        ->field('t.id,if(t.id=' . $c . ',"yes","no")idip,(select count(u.id) from u where id_g=' . session('user.id') . ' and u.id_c=t.id)u_count,t.id_parent,t.name,display.id display,display.tag,display.select_data,display.type,if(type like "*%",left(type,1),null)bixu,if(type like "%adds%","adds",null)adds')
                        ->order('t.id,display.orderby asc')
                        ->where($map)->select();

        $newdata = [];
        foreach ($data as $v) {

            $select_data = explode('|', $v['select_data']);
            foreach ($select_data as $k2 => $v2) {
                $select_data[$k2] = explode('/', $v2);
            }

            $display[$v['id']][$v['display']] = [
                'display' => $v['display'],
                'tag' => $v['tag'],
                'type' => $v['type'],
                'shiji' => ['shiji' => null, 'str' => $select_data[0]],
                'bixu' => strpos($v['type'], '*') === false ? "" : '*',
                'adds' => strpos($v['type'], 'adds') === false ? "" : 'adds',
                'select_data' => $select_data
            ];
            $newdata[$v['id']]['id'] = $v['id'];
            $newdata[$v['id']]['pId'] = $v['id_parent'];
            $newdata[$v['id']]['name'] = $v['name'];
            $newdata[$v['id']]['idip'] = $v['idip'];
            $newdata[$v['id']]['u_count'] = $v['u_count'];
        }

        foreach ($newdata as $k => $v) {
            $newdata[$k]['display'] = array_values($display[$k]);
        }
        return array_values($newdata);
    }

    public function u_addpage($c) {
        $data['tree'] = $this->display_return($c);
        foreach ($data['tree'] as $v) {

            if ($v['id'] == $c) {
                $this->title = '添加：' . $v['name'];
            }
        }

        $this->data = json_encode($data['tree'][0]['display']);
        $this->c = $c;
        $this->door = M('t')->join('u on u.id_c=t.id')->field('concat("index/index?c=",t.id)door,t.name,count(u.id)u_count')->group('t.id')
                        ->where(['u.id_g' => session('user.id'), 'u.id_c' => array('neq', '38')])->select();
        $this->display();
    }

    public function u_del($u) {
        if (IS_POST) {
            $c = M('u')->where(['id' => $u])->getField('id_c');
            $res = M('u')->where(['id' => $u])->delete();
            if ($c) {
                $this->success($this->shiji_return(I('c')), U('index/index?c=' . $c));
            } else {
                $this->error('删除产品失败');
            }
        }
    }
//$str, '请输入') > 0 || strpos($str, '请上传') > 0 || strpos($str, '选择城市') > 0
//substr_count($v['str'], '请输入')>0 || substr_count($v['str'], '请上传')>0 || substr_count($v['str'], '选择城市')>0
    public function u_add($c, $shijistrs) {
        if (IS_POST) {
            foreach ($shijistrs as $k => $v) {
                if ($v['bixu'] == "*" && is_array($v['str'])) {
                    $this->error($v['tag'] . '必须输入  ');
                    die;
                } else if (mb_strpos($str, '请输入') >0 || mb_strpos($str, '请上传')>0 || mb_strpos($str, '选择城市') >0) {
                    $this->error($v['str']);
                    die;
                }
                if (!is_array($v['str'])) {
                    $data[] = ['id_display' => $v['id_display'],
                        'str' => $v['str'],
                        'id_u' => ''];
                }
                if (!is_array($v['str']) && strpos($v['type'], 'sku') > 0) {
                    $sku[$k] = $v['str'];
                }
            }
            $sku = implode('/', $sku);
            try {
                $u = M('u')->add(['id_g' => session('user.id'), 'id_c' => $c, 'sku' => $sku]);
                !$u && E('货号已存在:' . M()->getDbError());

                foreach ($data as $k => $v) {
                    $data[$k]['id_u'] = $u;
                }
                M('shiji')->addALL($data);
                $this->success($sku . '添加成功', U('index/index?c=' . $c));

            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        }
    }

    public function shiji_save($shiji, $str) {
        if (IS_POST) {
            if (mb_strpos($str, '请输入') >0 || mb_strpos($str, '请上传')>0 || mb_strpos($str, '选择城市') >0) {
                
                $this->error($str);
                die;
            }
            $model = new \Think\Model;
            $model->startTrans();
            M('shiji')->where(['id' => $shiji])->save(['str' => $str]);
            $sql1 = M('shiji')
                            ->join('u on u.id=shiji.id_u')->join('shiji s2 on s2.id_u=u.id')
                            ->join('display on display.id=s2.id_display')
                            ->where('shiji.id=' . $shiji . ' and display.type like "%sku%" ')
                            ->field('u.id,u.id_c,group_concat(s2.str order by tag SEPARATOR"/")sku')->find();
            try {
                M('u')->where(['id' => $sql1['id']])->save(['sku' => $sql1['sku'] ?: '']);
                $model->commit();
                $this->success($this->shiji_return(I('c')));
            } catch (\Exception $ex) {
                $model->rollback();
                $this->error('货号已存在:u.sku错误 ' . $sql1['sku']);
            }
        }
    }

    public function shiji_add($u, $display, $str) {
        if (IS_POST) {
            if (mb_strpos($str, '请输入') >0 || mb_strpos($str, '请上传')>0 || mb_strpos($str, '选择城市') >0) {
                $this->error($str);
                die;
            }
            $res = M('shiji')->add(['id_u' => $u, 'id_display' => $display, 'str' => $str]);
            if ($res) {
                $this->success($this->shiji_return(I('c')));
            } else {
                $this->error('添加失败');
            }
        }
    }

    public function shiji_del($id) {
        if (IS_POST) {
            $res = M('shiji')->where(['id' => $id])->delete();
            if ($res) {
                //print_r($shijidata);exit;
                $this->success($this->shiji_return(I('c')));
            } else {
                $this->error('删除失败');
            }
        }
    }

    public function upload() {
        $upload = new \Think\Upload(); // $upload->maxSize = 5 * 1024 * 1024;
        $upload->exts = array('jpg', 'gif', 'png', 'bmp', 'tif', 'jpeg', //图片 
            'zip', 'RAR', 'pdf', 'DXF', 'DWT', 'DWF', 'DWL',
            'xls', 'xlsx', 'txt', 'doc'); // 设置附件上传类型
        $upload->rootPath = './'; // 设置附件上传根目录 
        $upload->savePath = '659/' . session('user.id') . '/';  //保存路径
        $upload->subName = ''; //子目录创建方式，[0]-函数名，[1]-参数，多个参数使用数组
        $upload->saveName = date('YmdHis') . '.' . get_client_ip();
        $info = $upload->upload();
        if ($info) {
            foreach ($info as &$file) {
                $file['filepath'] = $file['savepath'] . $file['savename'];
            }
            echo json_encode(array(
                // 'url' => '306/app/' . $file['filepath'],
                'url' => $file['filepath'],
                'title' => htmlspecialchars($_POST['pictitle'], ENT_QUOTES), 'original' => $file['savename'],
                'state' => 'SUCCESS'
            ));
        } else {
            echo json_encode(array('state' => $upload->getError()));
        }
    }

}

?>